

import 'package:erp/Entity/ProductType.dart';
import 'package:erp/Events/EventAddrs.dart';
import 'package:erp/Store/ProductStore.dart';
import 'package:erp/UI/Components/EventfulState.dart';
import 'package:erp/UI/Components/ListDividerGenerator.dart';
import 'package:erp/UI/Components/LogoScaffold.dart';
import 'package:erp/UI/Components/MessageDialog.dart';
import 'package:erp/UI/Components/QuestionDialog.dart';
import 'package:erp/UI/Pages/BasicInformationManagementPages/ProductTypePages/ProductTypeEditDialog.dart';
import 'package:erp/global.dart';
import 'package:flutter/material.dart';

class ProductTypePage extends StatelessWidget {
  bool selectionMode;

  ProductTypePage([this.selectionMode = false]);

  @override
  Widget build(BuildContext context) => ProductTypeStateful(this);
}

class ProductTypeStateful extends StatefulWidget {
  ProductTypePage param;

  ProductTypeStateful(this.param);
  @override
  State<StatefulWidget> createState() => ProductTypeState(param);

}

class ProductTypeState extends EventfulState<ProductTypeStateful> {
  List<ProductType> items = ProductStore.productTypes;
  ProductTypePage param;

  ProductTypeState(this.param);

  @override
  void initState() {
    eventIds = [
      bus.subscribe<List<ProductType>>(Events.PRODUCTTYPE_SELECT_SUCCESS, (bus, data){setState(() {});}),
      bus.subscribe<ProductType>(Events.PRODUCTTYPE_INSERT_SUCCESS, (bus, data){setState(() {});}),
      bus.subscribe(Events.PRODUCTTYPE_INSERT_ERROR, (bus, data){setState(() {
        showMessageDialog(context, title: "قوشۇش مەغلۇپ بولدى!", content: data.toString());
      });}),
      bus.subscribe(Events.PRODUCTTYPE_UPDATE_SUCCESS, (bus, data){setState(() {});}),
      bus.subscribe(Events.PRODUCTTYPE_UPDATE_ERROR, (bus, data){setState(() {
        showMessageDialog(context, title: "يىڭىلاش مەغلۇپ بولدى!", content: data.toString());
      });}),
      bus.subscribe(Events.PRODUCTTYPE_DELETE_SUCCESS, (bus, data){setState(() {});}),
      bus.subscribe(Events.PRODUCTTYPE_DELETE_ERROR, (bus, exception){setState(() {
        showMessageDialog(context, title: "ئۆچۈرۈش مەغلۇپ بولدى!", content: exception.toString());
      });}),
    ];
    super.initState();
  }

  @override
  Widget build(BuildContext context) {


    return LogoScaffold(
      title: "تاۋار تۈرىنى باشقۇرۇش",
      assetsLogoName: "assets/pictures/abc.png",
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () async {
          var type = ProductType(imgurl: "");
          var result = await showProductTypeEditDialog(context, type, mode: DialogOpenMode.ADD) ?? false;
          if (result){
            if (type.name?.isEmpty ?? true){
              showEmptyAlertDialog();
              return;
            }
            bus.publish(Events.PRODUCTTYPE_INSERT_REQUEST, type);
          }
        },
      ),
      heroName: "PeoductTypePageLogoHero",
      contentDelegate: SliverChildListDelegate(ListDividerGenerator(items.map((item) => buildItem(context, item)).toList(), Divider()).items),
      useSearchBar: true,
    );
  }

  Widget buildItem(BuildContext context, ProductType data){
    return ListTile(
      leading: loadImage(data.imgurl),
      title: Text(data.name),
      trailing: Wrap(
        direction: Axis.horizontal,
        children: <Widget>[
          IconButton(
            icon: Icon(Icons.edit),
            onPressed: ()async {
              var type = ProductType(
                id: data.id,
                name: data.name,
                imgurl: data.imgurl
              );
              var result = await showProductTypeEditDialog(context, type, mode: DialogOpenMode.EDIT) ?? false;
              if (result){
                if (type.name?.isEmpty ?? true){
                  showEmptyAlertDialog();
                  return;
                }
                bus.publish(Events.PRODUCTTYPE_UPDATE_REQUEST, type);
              }
            },
          ),
          IconButton(
            icon: Icon(Icons.delete),
            onPressed: () async {
              var result = await showQuestionDialog(context, title: "ئەسكەرتىش", content: "نۆۋەتتىكى تۈرنى ئۆچۈرۋەتمەكچى بولۇۋاتىسىز، جەزىملەشتۈرەمسىز؟") ?? false;
              if (result){
                bus.publish(Events.PRODUCTTYPE_DELETE_REQUEST, data);
              }
            },
          ),
        ],
      ),
      onTap: (){
        if (param.selectionMode)
          Navigator.of(context).pop(data);
      },
    );
  }

  Image loadImage(String url){
    Image image;
    try {
      image = Image.network(url, width: 38.0, height: 38.0,);
    }
    catch (exception){
      image = Image.asset("assets/pictures/picture.png", width: 38.0, height: 38.0,);
    }
    return image;
  }

  void showEmptyAlertDialog(){
    showMessageDialog(context, title: "ئەسكەرتىش", content: "تۈر ئىسمى قۇرۇق بولۇپ قالسا بولمايدۇ، قايتىدىن كىرگۈزۈڭ");
  }
}

